﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using spbtzb;
using System.IO;
using System.Text;

public partial class Back_ImageList : System.Web.UI.Page
{
    protected string strConnection = spbtzb.ConString.ConnString;
    #region Field

    private Boolean session_Logined
    {
        set
        {
            Session["Logined"] = value;
        }
        get
        {
            return Session["Logined"] == null ? false : Convert.ToBoolean(Session["Logined"]);
        }
    }
    #endregion
    protected void Page_Load(object sender, EventArgs e)
    { 
        //this.Page.Title = "图片管理页面";
        if (session_Logined == false)
        {
            Response.Redirect("Login.aspx?ErrorMessage=" + "您未登录，请在此登录");
        }
        if (!IsPostBack)
        {           
            BindDataListInit();
        }
    }

    protected void gvDict_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvDict.PageIndex = e.NewPageIndex;
        BindDataList();
    }

    private void BindDataListInit()
    {
        DataTable dt = AccessHelper.ExecuteDataTable(strConnection, CommandType.Text, "SELECT * FROM ImageList WHERE Type = '" + ddlImageType.SelectedValue.Trim() + "' Order By ID DESC");
        
        if (dt == null || dt.Rows.Count == 0)
        {
             btn_sumit.Visible = false;
             ipt_HdnSelectedValues.Value = ",";
        }
        else
        {
            btn_sumit.Visible = true;
            StringBuilder sb = new StringBuilder();
            sb.Append(",");
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["IsDisplay"] != null && Convert.ToBoolean(dr["IsDisplay"]) == true
                    && dr["ID"] != null)
                {
                    sb.Append( dr["ID"].ToString() + ",");
                }                 
            }
            if (sb.Length > 0)
            {
                this.ipt_HdnSelectedValues.Value = sb.Remove(sb.Length - 1, 1).ToString(); // 干掉最后一个逗号
            }
        }
        gvDict.DataSource = dt;
        gvDict.DataBind();    
    }

    private void BindDataList()
    {
        DataTable dt = AccessHelper.ExecuteDataTable(strConnection, CommandType.Text, "SELECT * FROM ImageList WHERE Type = '" + ddlImageType.SelectedValue.Trim() + "' Order By ID DESC");

        if (dt == null || dt.Rows.Count == 0)
        {
            btn_sumit.Visible = false;
            ipt_HdnSelectedValues.Value = ",";
        }
        else
        {
            btn_sumit.Visible = true;     
        }
        gvDict.DataSource = dt;
        gvDict.DataBind();
    }


    protected void btn_sumit_Click(object sender, EventArgs e)
    {
        //string SQL;
        //for(int i = 0; i<ImageDataList.Items.Count;++i)
        //{
        //    if (((CheckBox)ImageDataList.Items[i].FindControl("IsDisplayCheckBox")).Checked == true)
        //        SQL = "UPDATE ImageList SET IsDisplay='Y' WHERE [ID] =" + ((Label)ImageDataList.Items[i].FindControl("lbl_ID")).Text;
        //    else
        //        SQL = "UPDATE ImageList SET IsDisplay='N' WHERE [ID] =" + ((Label)ImageDataList.Items[i].FindControl("lbl_ID")).Text;
        //    AccessHelper.ExecuteNonQuery(strConnection, CommandType.Text, SQL);
        //}

        string SQL;
        int iret = 0;
        // int iSize = spbtzb.AuthenCtr.CountInstances(this.ipt_HdnSelectedValues.Value, ",");
        String strIDs = this.ipt_HdnSelectedValues.Value;
        String strIDsEx = strIDs.TrimStart(',');
        String[] ids = strIDsEx.Split(',');
        SQL = "UPDATE ImageList SET IsDisplay=false WHERE [Type] = '" + this.ddlImageType.SelectedValue + "'";
        iret = AccessHelper.ExecuteNonQuery(strConnection, CommandType.Text, SQL);     
        if (iret <= 0)
        {     
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作失败，请重新操作或联系管理员！');", true);
            return;
        }
        foreach (String id in ids)
        {
            SQL = "UPDATE ImageList SET IsDisplay=true WHERE [ID] =" + Convert.ToInt32(id).ToString();
            iret = AccessHelper.ExecuteNonQuery(strConnection, CommandType.Text, SQL); // rubish code, must be changed
            if (iret <= 0)
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作失败，请重新操作或联系管理员！');", true);
                return;
            }
        }       
        //for (int i = 0; i<gvDict.Rows.Count; ++i)
        //{
        //    if (((HtmlInputCheckBox)gvDict.Rows[i].Cells[1].Controls[1]).Checked == true)
        //        SQL = "UPDATE ImageList SET IsDisplay=true WHERE [ID] =" + ((Label)gvDict.Rows[i].FindControl("lbl_ID")).Text;
        //    else
        //        SQL = "UPDATE ImageList SET IsDisplay=false WHERE [ID] =" + ((Label)gvDict.Rows[i].FindControl("lbl_ID")).Text;
        //    iret = AccessHelper.ExecuteNonQuery(strConnection, CommandType.Text, SQL);
        //}
        ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作成功！');", true);    
    }

    protected void gvDict_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "DeleteContent": // modified by shiney
                ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(LinkButton), "tip", "confirm(您真的要删除这篇留言吗？);", true); 
                String strID = e.CommandArgument.ToString();
                string ImageUrl = "~/imagesUpload/" + AccessHelper.ExecuteScalar(strConnection, CommandType.Text, "SELECT ImageURL FROM ImageList WHERE [ID] =" + strID);
                File.Delete(Server.MapPath("ImageUrl"));
                int iret = AccessHelper.ExecuteNonQuery(strConnection, CommandType.Text, "DELETE FROM ImageList WHERE [ID] =" + e.CommandArgument.ToString()); //no judgement = =!
                if (iret <= 0)
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('操作失败，请重新操作或联系管理员！');", true);
                    return;
                }
                ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('删除操作成功!');", true);
                String strSelected = this.ipt_HdnSelectedValues.Value;
                String strTemp = "," + strID;
                if (strSelected.Contains(strTemp))
                {
                    this.ipt_HdnSelectedValues.Value = strSelected.Replace(strTemp, "");
                }
                BindDataList();

                break;
            default:
                break;
        }
    }

    protected void ddlImageType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindDataListInit();
    }
    protected void gvDict_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItemIndex < 0) return;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // 来个垃圾办法解决问题
            HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)e.Row.FindControl("IsDisplayCheckBox");
            if (ChkSelected == null) return;
            String strid = ChkSelected.Value;
            String strIDs = this.ipt_HdnSelectedValues.Value;
            String strIDsEx = strIDs.TrimStart(',');
            String[] ids = strIDsEx.Split(',');
            foreach (String id in ids)
            {
                if (strid == id)
                {
                    ChkSelected.Checked = true;
                    return;
                }
            }
        }
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    if (ipt_HdnSelectedValues.Value.IndexOf(((HtmlInputCheckBox)e.Row.Cells[1].FindControl("IsDisplayCheckBox")).Value) >= 0)
        //    {
        //        HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)e.Row.Cells[1].FindControl("IsDisplayCheckBox");
        //        ChkSelected.Checked = true;
        //    }           
        //}
    }


}//class
